<?php

namespace App\Admin\Controllers;

use App\Models\FhProduct;
use App\Models\FhProductContent;
use App\Models\FhCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class FhProductController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new FhProduct(), function (Grid $grid) {
            $grid->model()->orderBy('id','desc');
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('url');
            $grid->column('img')->display(function ($img) {
                return explode(',', $img);
            })->image('',60,40);
            
            $grid->column('Introduction');
            $grid->column('banners')->image('',100,80);
             $grid->column('hot','是否热门')->switch();
            $grid->column('sort')->editable();
            $grid->column('created_at');
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('name');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new FhProduct(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('url');
            $show->field('img');
            $show->field('keyword');
            $show->field('description');
            $show->field('Introduction');
            $show->field('banners');
            $show->field('sort');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make( FhProduct::with(['content','list']), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->text('url')->required();
            $form->select('pid')->options(FhCategory::selectOptions())->required();
            $form->multipleImage('img','多图上传')->thumbnail('small',300,300)->required()->
            move('images/'.date("Ymd",time()))->sortable()->help("排序第一的图片为缩略图，点击图片箭头可排序,请上传相同分辨率图片 最佳为 600*600")->saving(function ($value) {
                // 转化成json字符串保存到数据库
                    return implode(',',$value);
            });
            $form->multipleImage('slide','侧边栏图片')->thumbnail('small',300,300)->required()->
            move('images/'.date("Ymd",time()))->sortable()->help("图片为缩略图，点击图片箭头可排序,请上传相同分辨率图片最佳为 600*600")->saving(function ($value) {
                // 转化成json字符串保存到数据库
                    return implode(',',$value);
            });
            $form->text('keyword');
            $form->text('description');
            $form->text('Introduction')->required();
            $form->image('banners')->uniqueName()->required()->move('images/'.date("Ymd",time()))->help("最大宽度1200,高度450");
            $form->file('video','产品视频')->accept('mp4')->uniqueName()->maxSize(150*1024)->move('videos/'.date("Ymd",time()))->help("支持MP4格式视频");
            $form->switch('video_show',"视频是否展示")->options([0=>'隐藏',1=>'展示'])->default(1);
            $form->switch('show',"产品是否展示")->options([0=>'隐藏',1=>'展示'])->default(1);
            $form->switch('hot','热门')->options([0=>'正常',1=>'热门'])->default(0);
            $form->number('sort')->default(1);
            $form->hidden('thumb');
            $form->hasMany('content', __('产品内容'), function (Form\NestedForm $form) {
                $form->text('t_name')->required();
                $form->editor('t_content')->height(100)->required();
                $form->switch('show')->default(1);
                $form->number('sort')->default(1);
            })->required();

            $form->hasMany('list', __('SDK开发包'), function (Form\NestedForm $form) {
                $form->text('r_name',"文件名称")->required();
                $form->textarea('r_desc',"文件备注")->required();
                $form->radio('r_type',"文件类型")->options([1=>"开发包",2=>"说明书",3=>"规格书"])->default(1);
                $form->radio('r_addr',"存储地址")->options([1=>"百度云",2=>"本地上传"])->default(1);               
                $form->text('r_url','百度云地址,请输入带 http的链接');                           
                $form->file('n_url','上传文件')->maxSize(150*1024);                     
                $form->switch('show','是否显示')->default(1);
            })->required();

            $form->saving(function (Form $form) {
                $ids = $form->model()->id; 
                if (!$form->model()->id) {
                    $pattern = '/[?\&.\{\}#\s]/';  // 正则表达式
                    $isValid = preg_match($pattern,  $form->url) === 1; // 验证逻辑
                    if($isValid){
                        throw new \Exception('路由地址包含?&.{}# 空格特殊字符');
                    }
                }
                if($form->img){
                    $img = explode(",",$form->img);
                    $thumb=explode(".", $img[0]);
                    $form->thumb=$thumb[0].'-small.'.$thumb[1];
                    $form->img = implode(',',$img);
                }
                
            });

            $form->saved(function (Form $form, $result) {
                // 判断是否是新增操作
               $pids = $form->input('pid');
                if ($form->isCreating()) {
                    // 自增ID
                    $newId = $result;
                    // 也可以这样获取自增ID
                    $newId = $form->getKey();
                    
                    if (! $newId) {
                        return $form->error('数据保存失败');
                    }
                    if($form->input('content')){
                        $datas = [];
                        foreach ($form->input('content') as $vals)
                        {
                            $val['product_id'] = $newId;
                            $val['t_name'] = $vals['t_name'];
                            $val['t_content'] = $vals['t_content'];
                            $val['show'] =$vals['show'];
                            $val['sort'] = $vals['sort'];
                            $datas[] = $val;
                        }
                      $form->content = $datas;
                       
                    }

                    if($form->input('list')){
                        $dataed = [];
                        foreach ($form->input('list') as $vals)
                        {
                           
                            $val['p_id'] = $pids;
                            $val['r_name'] = $vals['r_name'];
                            $val['r_addr'] = $vals['r_addr'];
                            $val['r_desc'] = $vals['r_desc'];
                            $val['show'] = $vals['show'];
                            $val['r_url'] = $vals['r_url'];
                            $val["n_url"]= $vals["n_url"];
                            $val["product_id"]= $newId;
                            $dataed[] = $val;
                        }
                      $form->list = $dataed;
                    }
                    return;
                }
                // 修改操作
            });

            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    public function get(){
        $top = new FhProduct();
        $data = $top->select('id','name as text')->get();
        return response()->json($data);

    }
}
